<template>
  <view class="container">
    <ve-card :title="item.feeName" type="none" fold v-for="item in orderFeeList" :key="item.id">
      <template #status>
        <view class="status-2">{{ item.feeTypeName }}</view>
        <view class="status-3">{{ item.costTypeName }}</view>
      </template>
      <template v-if="item.orderInfo">
        <ve-cell-price :label="costType == 0 ? '应收金额' : '应付金额'" :value="item.totalAmount"></ve-cell-price>
        <ve-cell-price :label="costType == 0 ? '待收金额' : '待付金额'" :value="item.waitPayAmount"></ve-cell-price>
        <ve-cell-val label="订单号" :value="item.orderInfo.orderNo" />
        <ve-cell-val label="承租人" :value="item.orderInfo.memberName" />
        <ve-cell-val label="车牌号" :value="item.orderInfo.licenseNo" />
        <ve-cell label="租赁周期">
          <view
            >{{ item.orderInfo.expectedUseCarTime }} - {{ item.orderInfo.expectedReturnCarTime }}
            <view class="c3 fs30 fw400">租期：{{ item.orderInfo.leaseNumberStr }}</view>
          </view>
        </ve-cell>
      </template>

      <FeeTable :data="item" mode="confirm"></FeeTable>
      <ve-gap size="24" />
    </ve-card>
    <!-- 表单 -->
    <ve-form ref="veFormRef" :model="form" :rules="rules">
      <ve-card>
        <ve-form-item :label="costName + '金额'" unit="元" required>
          <ve-input-number v-model="form.actualAmount" :precision="2" disabled />
        </ve-form-item>
        <ve-form-item
          :label="costName + '方式'"
          required
          prop="paymentWay"
          labelTooltipContent="收/付款方式支持在系统管理菜单下的收支账号管理页面进行配置。"
        >
          <ve-picker-inline
            v-model="form.paymentWay"
            placeholder="请选择"
            :range="paywayEnum"
            unit="arrowRight"
            @change="typeChange"
          ></ve-picker-inline>
        </ve-form-item>
        <ve-form-item v-if="form.paymentWay == -1" label="结算主体" required prop="account">
          <ve-picker-inline v-model="form.account" placeholder="请选择" :range="accountList" unit="arrowRight" />
        </ve-form-item>
        <ve-form-item v-else :label="costName + '账号'" labelTooltipContent="收/付款账号支持在系统管理菜单下的收支账号管理页面进行配置。">
          <ve-picker-inline v-model="form.account" placeholder="请选择" :range="accountList" unit="arrowRight"></ve-picker-inline>
        </ve-form-item>
        <ve-form-item v-if="form.paymentWay && form.paymentWay != -1" :label="costName + '时间'" required prop="paymentTime">
          <ve-date-picker v-model="form.paymentTime" title="时间"></ve-date-picker>
        </ve-form-item>
        <ve-form-item label="客户名称" required prop="customerName">
          <ve-input v-model="form.customerName" placeholder="请输入" />
        </ve-form-item>
        <ve-form-item :label="costName == '收款' ? '客户付款账号' : '客户收款账号'">
          <ve-input v-model="form.customerAccount" placeholder="请输入" />
        </ve-form-item>
        <ve-form-item label="结算备注" :borderBottom="false" labelPosition="top">
          <ve-input type="textarea" maxlength="200" v-model="form.settlementRemark" placeholder="请输入备注" />
        </ve-form-item>
      </ve-card>
    </ve-form>

    <view style="height: 280rpx">
      <ve-bottom-box>
        <view class="bottom-btns">
          <view class="amount">
            {{ costName }}金额：
            <text class="amount-num">
              {{ receiveAmount }}
            </text>
            <text class="amount-pic">元</text>
          </view>
          <view class="line"></view>
          <ve-button type="primary" @click="formSubmit" :loading="loading" size="long">确认</ve-button>
        </view>
      </ve-bottom-box>
    </view>
  </view>
</template>

<script setup>
  import { ref } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { feetoConfirmAPI, getAccountByPageDataAPI, getAccountByWayAndTypeAPI, feeSubmitAPI } from '@/api/order/lOrder'
  import FeeTable from './components/fee-table.vue'
  import { useLoadDataAndHotUpdateNavigateBack } from '@/hooks/useListNavigate'
  import { userStore } from '@/stores'

  const userInfoStore = userStore()
  const costType = ref(1)
  const costName = ref(null) //收款or付款
  const pagefrom = ref(null) //判断页面回退 expense详情页  mergeConfirm合并页
  const receiveAmount = ref(0)
  const accountList = ref(null) //收付款账号
  const idList = ref([])
  const form = ref({})
  const orderFeeList = ref([])
  const disabledCostType = ref(false)

  const rules = ref({
    paymentTime: {
      required: true,
      message: '请选择',
    },
    paymentWay: {
      required: true,
      message: '请选择',
    },
    actualAmount: {
      required: true,
      message: '请输入',
    },
    customerName: {
      required: true,
      message: '请输入',
    },
  })

  const getDetail = async () => {
    const res = await feetoConfirmAPI({ idList: idList.value })
    if (res.code != 200) return
    const result = res.result
    // 费用列表
    orderFeeList.value = result.orderFeeList.map((item) => {
      item.totalAmount = Math.abs(item.totalAmount)
      // 待支付金额
      item.waitPayAmount = Math.abs(item.receiveAmount)
      return item
    })
    // 费用相关
    receiveAmount.value = Math.abs(res.result.receiveAmount) //合计（取绝对值）
    const first_orderFee = orderFeeList.value[0] || {}
    // 初始化form
    form.value = {
      idList: idList.value,
      orderId: first_orderFee.orderId,
      actualAmount: receiveAmount.value,
      customerName: first_orderFee.orderInfo.memberName,
      paymentTime: first_orderFee.createTime,
      costType: result.costType,
    }
    // 押金抵扣为固定收付款方式
    if (form.value.payType != null) {
      disabledCostType.value = true
      form.value.paymentWay = res.result.payType.toString()
    }
    // 收付款类型
    costType.value = result.costType
    costType.value == 10 ? (costName.value = '收款') : (costName.value = '付款')
    getPaymentType()
  }

  // 收付款类型（方式）
  const paywayEnum = ref(null) //收付款方式
  const getPaymentType = () => {
    const is_offline = orderFeeList.value.every((item) => item.feeType == 1)
    console.log('is_offline', is_offline)

    const is_collection = orderFeeList.value.every((item) => item.costType == 10)
    console.log('is_collection', is_collection)

    // 是否包含租车押金和违章押金
    const is_contain_rent_violation = orderFeeList.value.some((item) => item.feeNameId == 12 || item.feeNameId == 13)
    console.log('is_contain_rent_violation', is_contain_rent_violation)

    let is_show_jialian = false
    if (orderFeeList.value.length == 1 && is_collection && form.value.actualAmount > 0) {
      is_show_jialian = true
    } else if (orderFeeList.value.length > 1) {
      if (is_collection && form.value.actualAmount > 0) {
        is_show_jialian = true
      } else if (!is_collection && form.value.actualAmount > 0) {
        is_show_jialian = true
      }
    }
    console.log('is_show_jialian', is_show_jialian)

    const enterpriseDetail = ref({})
    userInfoStore.setEpDetail(false).then((res) => {
      console.log('setEpDetail', res)
      enterpriseDetail.value = res

      console.log('嘉联聚合支付判断', enterpriseDetail.value.jialianEnabled, form.value.actualAmount)

      getAccountByPageDataAPI({ type: costType.value == 10 ? 0 : 1 }).then((res) => {
        let newarr = []
        const data = res.result

        data.forEach((i, index) => {
          if (i.way != '1' && i.way != '2' && i.way != '3' && i.way != '5' && disabledCostType.value) {
            newarr.push(i)
          } else if (i.way != '1' && i.way != '2' && i.way != '3' && i.way != '4' && i.way != '5' && !disabledCostType.value) {
            newarr.push(i)
          }

          /**
           * 不显示嘉联聚合支付
           * enterpriseDetail.value.jialianEnabled: 0 未开通嘉联聚合支付
           * actualAmount: 收款金额小于等于0
           * is_offline: 不是线下费用时
           * is_show_jialian: 是否显示嘉联聚合支付，默认不显示
           * is_contain_rent_violation: 是否包含租车押金和违章押金
           */
          if (enterpriseDetail.value.jialianEnabled == 0 || !is_show_jialian || !is_offline || is_contain_rent_violation) {
            newarr = newarr.filter((el) => el.way != '-1')
          }

          if (data.length == index + 1) {
            var children = newarr.map((childItem) => {
              return {
                value: childItem.way,
                label: childItem.wayStr,
                type: childItem.type,
              }
            })
            paywayEnum.value = children
          }
        })
        if (form.value.paymentWay) {
          typeChange(form.value.paymentWay)
        }
      })
    })
  }

  // 账号
  const typeChange = (value) => {
    if (value == -1) {
      rules.value.account = {
        required: true,
        message: '请选择',
      }
    } else {
      delete rules.value.account
    }

    form.value.account = ''

    paywayEnum.value.forEach((el) => {
      if (el.value == value) {
        getAccountByWayAndTypeAPI({ way: Number(el.value), type: Number(el.type) }).then((res) => {
          var children = res.result.map((childItem) => {
            return {
              value: childItem.id,
              label: form.value.paymentWay != -1 ? childItem.account + '_' + childItem.bank : childItem.bank,
            }
          })

          if (children.length == 1 && form.value.paymentWay == -1) {
            form.value.account = children[0].value
          }

          accountList.value = children
        })
      }
    })
  }
  // 提交
  const veFormRef = ref()
  const loading = ref(false)
  const formSubmit = () => {
    veFormRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true

        try {
          const res = await feeSubmitAPI({ ...form.value })
          if (res.code == 200) {
            if (form.value.paymentWay == -1) {
              const from =
                pagefrom.value == 'mergeConfirm' ? 'order/long-order/detail/mergeConfirmation' : 'order/long-order/detail/confirmExpenses'
              uni.navigateTo({
                url: `/pages/common/components/qrcode?id=${res.result}&from=${from}`,
              })
            } else {
              uni.showToast({
                icon: 'none',
                title: res.message,
              })
              setTimeout(() => {
                if (pagefrom.value == 'orderList') {
                  useLoadDataAndHotUpdateNavigateBack()
                }
                if (pagefrom.value == 'expense') {
                  uni.navigateBack({ delta: 1 })
                }
                if (pagefrom.value == 'mergeConfirm') {
                  uni.navigateBack({ delta: 2 })
                }
              }, 500)
            }
          } else {
            uni.showToast({
              icon: 'none',
              title: '请选择费项',
            })
            return false
          }
        } catch (error) {
          console.log('error', error)
          loading.value = false
        }
      } else {
        uni.pageScrollTo({
          duration: 100,
          scrollTop: 900000,
        })
      }
    })
  }
  onLoad((options) => {
    idList.value = JSON.parse(options.idList)
    pagefrom.value = options.pagefrom
    getDetail()
    if (options.pagefrom) {
      pagefrom.value = options.pagefrom
    }
  })
</script>

<style lang="less" scoped>
  .container {
    padding: 24rpx;
  }
  .status-2 {
    background: #e8f7ff;
    color: #3491fa;
    border: 2rpx solid #3491fa;
    border-radius: 450rpx;
    padding: 0 16rpx;
    height: 40rpx;
    line-height: 40rpx;
    font-size: 24rpx;
    margin-right: 10rpx;
    margin-left: 10rpx;
  }
  .status-3 {
    background: #fff7e8;
    color: #ff7d00;
    border: 2rpx solid #ff7d00;
    border-radius: 450rpx;
    padding: 0 16rpx;
    height: 40rpx;
    line-height: 40rpx;
    font-size: 24rpx;
    margin-right: 10rpx;
  }
  .line {
    width: 100%;
    background: #d8d8d8;
    height: 1rpx;
  }

  .fee-item {
    overflow-x: scroll;
    margin-top: 24rpx;
    .fee-table {
      width: 800rpx;
      .tlt {
        width: 100%;
        height: 88rpx;
        background: #f7f8fa;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        color: #8491a8;
        font-size: 24rpx;
        view:nth-child(1) {
          width: 320rpx;
          margin-left: 24rpx;
        }
        view:nth-child(2) {
          width: 160rpx;
        }
        view:nth-child(3) {
          width: 320rpx;
        }
      }
      .fee-first {
        width: 100%;
        margin: 32rpx 0 16rpx;
        background: #ffffff;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        color: #191c27;
        font-size: 28rpx;
        view:nth-child(1) {
          width: 320rpx;
          margin-left: 24rpx;
        }
        view:nth-child(2) {
          width: 160rpx;
        }
        view:nth-child(3) {
          width: 320rpx;
        }
      }
      .fee-other {
        margin-left: 22rpx;
        .twice {
          width: calc(100% - 20rpx);
          background: #f7f8fa;
          padding: 0 24rpx 24rpx;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          color: #191c27;
          font-size: 28rpx;
          view {
            margin-top: 24rpx;
          }
          view:nth-child(1) {
            width: 296rpx;
            margin-left: 24rpx;
          }
          view:nth-child(2) {
            width: 160rpx;
          }
          view:nth-child(3) {
            width: 320rpx;
          }
        }
        .third {
          width: calc(100% - 20rpx);
          background: #f7f8fa;
          padding: 0 24rpx 24rpx;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          color: #191c27;
          font-size: 28rpx;
          view:nth-child(1) {
            width: 248rpx;
            margin-left: 48rpx;
          }
          view:nth-child(2) {
            width: 160rpx;
          }
          view:nth-child(3) {
            width: 320rpx;
          }
        }
      }
    }
  }
  .bottom-btns {
    width: 100%;
    display: flex;
    flex-direction: column;
    .amount {
      color: #1e1e1e;
      font-size: 32rpx;
      font-weight: 400;
      display: flex;
      justify-content: flex-start;
      align-items: flex-end;
      margin: 12rpx 0 36rpx;
      .amount-num {
        color: #fe615a;
        font-size: 48rpx;
        font-weight: 600;
        line-height: 1;
      }
      .amount-pic {
        color: #fe615a;
        font-size: 24rpx;
        font-weight: 400;
        margin-left: 8rpx;
      }
    }
    .line {
      width: 100%;
      background: rgba(216, 216, 216, 0.3);
      height: 1px;
      margin-bottom: 32rpx;
    }
  }
  :deep(.ve_tooltip__popper) {
    width: 420rpx;
    line-height: 38rpx;
    white-space: normal;
  }
</style>
